<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <canvas id="cvs" width="500" height="200"></canvas>
    <div class="txt">恭喜你获得了500W</div>
  </body>
  <style>
    body{
      margin: 0;
      padding: 0;
    }
    #cvs {
      border: 1px solid #000;
    }
    .txt {
      position: absolute;
      left: 0;
      top: 0;
      width: 500px;
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: -1;
    }
  </style>
  <script>
     const box = document.querySelector("#cvs");
    //生成canvas对象
    const context = box.getContext("2d");
    //设置画布填充色
    context.fillStyle = "#ccc";
    //绘制矩形
    context.fillRect(0, 0, box.width, box.height);
    //设置是否按下标记
    let isDrag = false;
    function downFn(e) {
      console.log("down:", e);
      isDrag = true;
    }
    function moveFn(e) {
      if (isDrag) {
        const x = e.clientX - box.offsetLeft;
        const y = e.clientY - box.offsetTop;
        //绘制小圆来模拟笔
        context.beginPath();
        context.fillStyle = "#000";
        //图像合成，保证重叠的地方变透明
        context.globalCompositeOperation = "destination-out";
        context.arc(x, y, 5, (Math.PI / 180) * 0, (Math.PI / 180) * 360);
        context.fill();
      }
    }
    function upFn() {
      isDrag = false;
    }
    box.addEventListener("mousedown", downFn, false);
    box.addEventListener("mousemove", moveFn, false);
    box.addEventListener("mouseup", upFn, false);
  </script>
</html>
